package l1j.opqlo.假人系統;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
//import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.datatables.CharacterTable;
import l1j.server.server.utils.Random;
import l1j.server.server.utils.SQLUtil;

public class RobotTable {
	private static Logger _log = Logger.getLogger(RobotTable.class.getName());


	private static RobotTable _instance;

	public static RobotTable getInstance(){
		if(_instance == null){
			_instance = new RobotTable();
		}
		return _instance;
	}

	private ArrayList<String>_namelist = new ArrayList<String>();
	private ArrayList<String>_tilelist = new ArrayList<String>();
	private HashMap<String ,Integer>_polylist = new HashMap<String , Integer>();
	private HashMap<String ,Integer>_levelmentlist = new HashMap<String , Integer>();

	public void load(){
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM z_opqlo_Robot");
			rs = pstm.executeQuery();
			while (rs.next()) {
				String name = rs.getString("name");
				if(!CharacterTable.getInstance().CheckCharName(name)){
					_namelist.add(name);
					_polylist.put(name, rs.getInt("gfxid"));
					_levelmentlist.put(name, rs.getInt("metempsychosis"));
				}
				String title = rs.getString("title");
				if(title !=null){
					_tilelist.add(title);
				}
			}
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public String getRandomName(){
		final int size = _namelist.size();
		if(size ==1){
			String name = _namelist.get(0);
			_namelist.remove(name);
			return name;
		}
		if(size>1){
			String name = _namelist.get(Random.nextInt(size));
			_namelist.remove(name);
			return name;
		}
		return null;
	}
	
	public String getRandomTitle(){
		final int size = _tilelist.size();
		if(size ==1){
			String name = _tilelist.get(0);
			_tilelist.remove(name);
			return name;
		}
		if(size>1){
			String name = _tilelist.get(Random.nextInt(size));
			_tilelist.remove(name);
			return name;
		}
		return null;
	}

	public int getGfxId(final String name){
		return _polylist.get(name);
	}
	public int getLevelMent(final String name){
		return _levelmentlist.get(name);
	}
	public boolean checkName(final String name){
		return _namelist.contains(name);
	}

}
